<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-27 10:03:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-08-30 16:17:55
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\VaccineInject\components\Edit.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 疫苗注射记录-修改
-->
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElButton, ElInput, ElMessage } from 'element-plus'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
import { Table } from '@/components/Table'
import FoodRefer from './FoodRefer.vue'
import EnclosureList from './EnclosureList.vue'

import { useForm } from '@/hooks/web/useForm'
import { useIcon } from '@/hooks/web/useIcon'

import { required } from '@/utils/formRules'
import { spForageFormulaListApi } from '@/api/sp/food'
import { spFeedPlanSeeApi } from '@/api/sp/feed'
import { zcPastureListApi } from '@/api/fa/pasture'
import { spEnclosureListApi } from '@/api/fa/enclosure'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const iconAdd = useIcon({ icon: 'material-symbols:add' })
const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })
import { ucDeptListApi } from '@/api/uc/dept'
import { ucOrgDeptUserListApi } from '@/api/fa/user'

const myDeptList: any = wsCache.get('myDeptList')
const myUserList: any = ref(wsCache.get('myUserList'))
const userInfo: any = wsCache.get('userInfo')
const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])
const data = ref<any>({})
const actionType = ref('')
const e_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位

const rules = reactive({
  pasture_org_id: [required],
  name: [required],
  start_date: [required],
  end_date: [required],
  formula: [required]
})

const props = defineProps({
  id: {
    type: String,
    default: null
  }
})
// let weight = ref()
// 调用查看接口获取信息
const getSee = async () => {
  if (props.id) {
    await methods.setValues(data.value)
    const res = await spFeedPlanSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = res.data
      await getAllEnclosure(data.value.pasture_org_id)
      await methods.setValues(data.value)
      e_id.value = data.value?.detailed.length
      let aaa = data.value?.detailed
      aaa.forEach((element, index) => {
        element.e_id = index + 1
      })
      data.value.detailed = aaa
    }
    await DeptList(data.value.pasture_org_id)
  } else {
    data.value.detailed = []
    data.value.feedDetailedData = []
    await methods.setValues(data.value)
  }
}

const onCustomer = async (value) => {
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    data.value.pasture_user_id = ''
    data.value.pasture_user_name = ''
    await DeptList(value)
  }
  // pasture_org_id
  await getAllEnclosure(data.value.pasture_org_id)
  await methods.setValues(data.value)
}

const getAllEnclosure = async (val) => {
  let res = await spEnclosureListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.value.enclosureData = res.data
  }
}

// 管理员用户列表
const myUserListChange = async (value) => {
  myUserList.value = []
  data.value.admin_dept_id = value
  data.value.admin_user_id = ''
  data.value.admin_user_name = ''
  const params = {
    org_id: userInfo.default_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi(params)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    myUserList.value = res.data
  }
}
const DeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
  if (props.id) {
    await UserList(data.value.pasture_dept_id)
  }
}
const stateChangeAdminUser = async (value) => {
  data.value.admin_user_id = value
}
const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}
const UserList = async (value) => {
  data.value.pasture_dept_id = value
  await methods.setValues(data.value)
  newUserData.value = []
  const params = {
    org_id: data.value.pasture_org_id,
    dept_id: data.value.pasture_dept_id
  }
  const res = await ucOrgDeptUserListApi(params)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
}

const schemaAdd = reactive<FormSchema[]>([
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '牧场用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'name',
    component: 'Input',
    label: '计划名称'
    // onChange: nameChange
  },
  {
    field: 'start_date',
    component: 'DatePicker',
    label: '开始时间',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'end_date',
    component: 'DatePicker',
    label: '结束时间',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'note',
    component: 'Input',
    label: '备注'
  }
])
const schemaEdit = reactive<FormSchema[]>([
  {
    field: 'admin_dept_id',
    label: '管理部门',
    component: 'TreeSelect',
    componentProps: {
      data: myDeptList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: myUserListChange
    }
  },
  {
    field: 'admin_user_id',
    label: '管理用户',
    component: 'TreeSelect',
    componentProps: {
      data: myUserList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeAdminUser
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'name',
    component: 'Input',
    label: '计划名称'
  },
  {
    field: 'start_date',
    component: 'DatePicker',
    label: '开始时间',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'end_date',
    component: 'DatePicker',
    label: '结束时间',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'note',
    component: 'Input',
    label: '备注'
  }
])
const { register, methods, elFormRef } = useForm({
  schema: props.id ? schemaEdit : schemaAdd
})

const getFormData = async () => {
  let formData = await methods.getFormData()
  return {
    ...formData
  }
}

const onFormula = async (new_data) => {
  let formData: any = await methods.getFormData()
  if (!formData.pasture_org_id) {
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
  const res = await spForageFormulaListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    return res
  }
}

defineExpose({
  elFormRef,
  getFormData
})

const enclosure_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 20
  },
  {
    field: 'enclosure_id',
    label: '栏位',
    width: 150
  },
  {
    field: 'num',
    label: '存栏数'
  },
  {
    field: 'name',
    label: '饲料配方',
    width: 150
  },
  {
    field: 'threshold',
    label: '喂养阈值',
    width: 85
  },
  {
    field: 'time',
    label: '喂养时间',
    width: 180
  },
  {
    field: 'note',
    label: '备注'
  },
  {
    field: 'action',
    width: 60,
    fixed: 'right',
    label: '操作'
  }
])

/****************************** 明细配置 end ******************************/
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'enclosure_add_d':
      e_id.value++
      console.log(e_id.value, 'e_id')
      if (data.value.pasture_org_id) {
        data.value.detailed.push({ e_id: e_id.value, enclosure_num: '', threshold: '' })
        console.log(data.value.detailed, 'data.value.detailedDataEnclosure')
      } else {
        ElMessage.warning('请先选择牧场')
      }
      break
    case 'del_d':
      let row_i = data.value.detailedData.findIndex((item) => {
        return item.d_id == row.d_id
      })
      data.value.detailedData.splice(row_i, 1)
      break
    case 'enclosure_del_d':
      let row_e = data.value.detailedDataEnclosure.findIndex((item) => {
        return item.e_id == row.e_id
      })
      data.value.detailedDataEnclosure.splice(row_e, 1)
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 初始化 start ******************************/
const init = async () => {
  await getSee()
}
init()

const changeEnclosure = async (value) => {
  data.value.detailed.forEach((element) => {
    if (element.e_id == value[3]) {
      element.enclosure_num = value[2]
    }
  })
}
const changeFormula = async (value) => {
  data.value.detailed.forEach((element) => {
    if (element.e_id == value[3]) {
      element.threshold = value[2]
    }
  })
}

/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="register" :data="data" />
    </ContentWrap>
    <ContentWrap title="选择喂养栏位">
      <div class="mb-10px">
        <ElButton circle :icon="iconAdd" @click="action('enclosure_add_d')" title="新增行" />
      </div>
      <Table :columns="enclosure_columns" :data="data.detailed" :selection="false" :border="true">
        <template #enclosure_id="{ row }">
          <EnclosureList
            v-model="row.enclosure_id"
            :tree="data.enclosureData"
            :eId="row.e_id"
            @change="changeEnclosure"
            nameField="name"
            relNameField="name"
            :modelName="row.enclosure_name"
          />
        </template>
        <template #num="{ row }">
          <ElInput v-model="row.enclosure_num" :disabled="true" />
        </template>
        <template #name="{ row }">
          <FoodRefer
            v-model="row.forage_formula_id"
            :getListApi="onFormula"
            :response="{ count: 'count', data: 'data' }"
            title="选择饲料（双击选择）"
            nameField="name"
            relNameField="name"
            valueField="id"
            :crudSchemas="[
              { field: 'name', label: '饲料名称', search: { show: true } },
              { field: 'note', label: '备注', search: { show: true } }
            ]"
            :eId="row.e_id"
            :modelName="row.forage_formula_name"
            @change="changeFormula"
          />
        </template>
        <template #threshold="{ row }">
          <ElInput v-model="row.threshold" />
        </template>
        <template #time="{ row }">
          <ElTimePicker v-model="row.feed_time" style="width: 150px" valueFormat="HH:mm:ss" />
        </template>
        <template #note="{ row }">
          <ElInput v-model="row.note" />
        </template>
        <template #action="{ row }">
          <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
        </template>
      </Table>
    </ContentWrap>
  </div>
</template>
